//
//  ViewController.m
//  数据的增删改查
//
//  Created by Clement_Gu on 16/3/14.
//  Copyright © 2016年 小白. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UITextField *txtID;
@property (nonatomic,strong)UITextField *txtName;
@property (nonatomic,strong)UITextField *txtAge;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *mArrList;
@property (nonatomic,strong)NSMutableArray *mArrGetList;
@end

//plist文件的增删改查

@implementation ViewController
//懒加载 重写getter
-(NSMutableArray *)mArrList
{
    if (_mArrList == nil) {
        //判断文档是否存在 如果存在则在原文件中读取
        NSFileManager *fmManager = [NSFileManager defaultManager];
        if ([fmManager fileExistsAtPath:[self plistPath]]) {
            //取数据
            NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:[self plistPath]];
            _mArrList = arr;
        }
        else
        {
            //否则新建数据
            _mArrList  = [NSMutableArray array];
        }
    }

    return _mArrList;
}


//在页面加载前
-(void)loadView
{
    //将ViewContrller中的View变为UIContrl的对象
    UIControl *control = [[UIControl alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self setView:control];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.txtID = [self buidTxt:CGRectMake(120, 50, 150, 35) AndKeboardType:UIKeyboardTypeNumberPad];
    self.txtName = [self buidTxt:CGRectMake(120, 120, 150, 35) AndKeboardType:UIKeyboardTypeNumbersAndPunctuation];
    self.txtAge = [self buidTxt:CGRectMake(120, 190, 150, 35) AndKeboardType:UIKeyboardTypeNumberPad];
    [self buidLabel:CGRectMake(70, 50, 50, 40) andText:@"学号"];
    [self buidLabel:CGRectMake(70, 120, 50, 40) andText:@"名字"];
    [self buidLabel:CGRectMake(70, 190, 50, 40) andText:@"年龄"];
    [self buidBtn:CGRectMake(15, 250, 50, 40) AndName:@"添加" AndEvent:@selector(add)];
    [self buidBtn:CGRectMake(65, 250, 50, 40) AndName:@"删除" AndEvent:@selector(remove)];
    [self buidBtn:CGRectMake(115, 250, 50, 40) AndName:@"修改" AndEvent:@selector(motify)];
    [self buidBtn:CGRectMake(165, 250, 50, 40) AndName:@"查找" AndEvent:@selector(resarch)];
    [self buidBtn:CGRectMake(215, 250, 80, 40) AndName:@"查找全部" AndEvent:@selector(findAll)];
    //添加表格
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(5, 300, 310, 250)];
    self.tableView = tableView;
    [self.view addSubview:tableView];
    //注册单元格模板
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    //声明代理
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //添加点击View页面的事件
    UIControl *control = self.view;
    //设置背景色
    self.view.backgroundColor = [UIColor whiteColor];
    [control addTarget:self action:@selector(resignView) forControlEvents:UIControlEventTouchUpInside];
    
//    UIControl *vc = [[UIControl alloc]init];
//    
//    [vc addTarget:self action:@selector(resignView) forControlEvents:UIControlEventTouchUpInside];
}
//创建textFile
-(UITextField *)buidTxt:(CGRect)frame AndKeboardType:(UIKeyboardType)keyboard
{
    UITextField *txtFileID = [[UITextField alloc]initWithFrame:frame];
    [txtFileID setBorderStyle:UITextBorderStyleRoundedRect];
    [txtFileID setKeyboardType:keyboard];
    [self.view addSubview:txtFileID];
    return txtFileID;
}
//创建label
-(void)buidLabel:(CGRect)frame andText:(NSString *)text
{
    UILabel *label = [[UILabel alloc]initWithFrame:frame];
    label.text = text;
    [self.view addSubview:label];
}
//创建button
-(void)buidBtn:(CGRect)frame AndName:(NSString *)name AndEvent:(SEL)sel
{
    UIButton *btn = [[UIButton alloc]initWithFrame:frame];
    [btn setTitle:name forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [btn addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

}
//点击空白取消编辑状态
-(void)resignView
{
    [self.view endEditing:YES];
}
//plist文件在沙盒的地址
-(NSString *)plistPath
{
    //沙盒路径 然后进入Documents
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //再从Documents里面添加plist
    NSString *filePath = [path stringByAppendingPathComponent:@"students.plist"];
    //返回plist路径
    return filePath;
}
//保存数据到plist文件（覆盖以前的数据）
-(void)saveData
{
    //写到文件
    [self.mArrList writeToFile:[self plistPath] atomically:YES];
}

//弹出框方法
-(void)showAlert:(NSString *)title AndMessage:(NSString *)message
{
    //弹出错误信息
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    //添加取消键
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    //弹到页面
    [self presentViewController:alert animated:YES completion:nil];
    //执行action
    [alert addAction:action];
}
//取数据
-(void)getData
{
    //取得students.plist文件的数据作为tableview显示的数据
    self.mArrGetList = [NSMutableArray arrayWithContentsOfFile:[self plistPath]];
    
}

-(void)add
{
    if (self.mArrList == nil) {
    //创建存储字典
    NSMutableDictionary *dic = [@{@"stuID":self.txtID.text,
                                  @"stuName":self.txtName.text,
                                  @"stuAge":self.txtAge.text}mutableCopy];
    //添加进数组
    [self.mArrList addObject:dic];
    //保存数据
    [self saveData];
    }
    else
    {
        //创建监控数据
        int count = 0;
       //遍历数组
        for (id element in self.mArrList){
            //判断数组里为MutableDictionary
            if ([element isKindOfClass:[NSMutableDictionary class]]) {
                //判断有没有重复的id
                if ([element[@"stuID"] isEqualToString:self.txtID.text]) {
                    [self showAlert:@"警告" AndMessage:@"此学生信息已经存在！"];
                    count++;
                }
            }
        }
        if (count == 0) {
            //创建存储字典
            NSMutableDictionary *dic = [@{@"stuID":self.txtID.text,
                                          @"stuName":self.txtName.text,
                                          @"stuAge":self.txtAge.text}mutableCopy];
            //添加进数组
            [self.mArrList addObject:dic];
            //保存数据
            [self saveData];

        }
    }
}
-(void)remove
{
    //1.遍历数组
    for (NSMutableDictionary *element in self.mArrList) {
        //2.以学生学号为判断条件
        if ([element[@"stuID"] isEqualToString:self
            .txtID.text]) {
            //执行删除操作
            [self.mArrList removeObject:element];
            //跳出
            break;
        }
    }
    //保存数据
    [self saveData];
}
-(void)motify
{
    //设定监测数据
    int count = 0;
    //1.遍历寻找
    for (NSMutableDictionary *element in self.mArrList) {
        //2.以学号为基准进行判断
        if ([element[@"stuID"] isEqualToString:self.txtID.text]) {
            //修改信息
            element[@"stuName"] = self.txtName.text;
            element[@"stuAge"] = self.txtAge.text;
            count++;
            break;
        }
        
        
    }
    //声明
    if (!count) {
        [self showAlert:@"信息错误" AndMessage:@"请输入正确的学号！"];

    }
    //保存数据
    [self saveData];
}
-(void)resarch
{
    //1.遍历
    for (NSMutableDictionary *element in self.mArrList) {
        //2.以学生ID进行搜索
        if ([element[@"stuID"] isEqualToString:self.txtID.text]) {
            //3.显示
            self.txtName.text = element[@"stuName"];
            self.txtAge.text = element[@"stuAge"];
            break;
        }
    }
}
-(void)findAll
{
    //取plist文件里面的数据
    [self getData];
        //刷新数据
        [self.tableView reloadData];

}
//设置section的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.mArrGetList.count;
}

//表格数据源@requied
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //第一层数组的元素为dictionary
    NSDictionary *dic = self.mArrGetList[section];
    //row的行数为dictionary的key的个数
    NSArray *arr = [dic allKeys];
    return  arr.count;
}


//单元格的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //复用单元格
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    //第一层数组的元素为dictionary
    NSDictionary *dic = self.mArrGetList[indexPath.section];
    //row的行数为dictionary的key的个数
    //并且排序
    NSArray *arr = [[dic allKeys] sortedArrayUsingSelector:@selector(compare:)];
//    NSMutableArray *mArr = [NSMutableArray array];
//        [mArr addObject:dic[@"stuID"]];
//        [mArr addObject:dic[@"stuName"]];
//        [mArr addObject:dic[@"stuAge"]];
   
    //单元格内容
//    cell.textLabel.text = mArr[indexPath.row];
    cell.textLabel.text = dic[arr[indexPath.row]];
    return cell;
}

//sectionhead 内容
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    //第一层数组的元素为dictionary
    NSDictionary *dic = self.mArrGetList[section];
   //显示ID作为段头
    return dic[@"stuID"];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
